package com.sun.java8;

import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

public class TestStream02 {
    @Test
    public void test01(){
        List<Person> peoples = Arrays.asList(
                new Person(1, "张四", 18),
                new Person(1, "张三", 18),
                new Person(3, "张五", 19),
                new Person(3, "张五", 19),
                new Person(3, "张五", 19),
                new Person(4, "张六", 21),
                new Person(4, "张六", 25)
        );
        peoples.stream()
                .forEach(x->{
                    x.setName(x.getName().substring(1) + "*");
                });
        System.out.println(peoples);
    }
    /*
    allMatch--检查是否匹配所有元素
    anyMatch--检查是否至少匹配一个元素
    noneMatch--检测是否没有匹配所有元素
    findFirst--返回第一个元素
    findAny--返回当前流中的任意元素
    count--返回流中元素的总个数
    max--返回流中的最大值
    min--返回流中最小值
     */
    @Test
    public void test02(){
        List<Person> peoples = Arrays.asList(
                new Person(1, "张四", 18),
                new Person(1, "张三", 18),
                new Person(3, "张五", 19),
                new Person(3, "张五", 19),
                new Person(3, "张五", 19),
                new Person(4, "张六", 21),
                new Person(4, "张六", 25)
        );
        //年龄之和
        Integer sum = peoples.stream()
                .map(x -> x.getAge())
                .reduce(0, (x, y) -> x + y);
        System.out.println(sum);
        System.out.println("========================");
        IntSummaryStatistics collect = peoples.stream()
                .collect(Collectors.summarizingInt(x -> x.getAge()));
        System.out.println(collect);
        System.out.println("=========================");
        //总数
        long count = peoples.stream().count();
        System.out.println(count);
        System.out.println("=========================");
        //平均值
        Double collect1 = peoples.stream()
                .collect(Collectors.averagingInt(x -> x.getAge()));
        System.out.println(collect1);
        System.out.println("=========================");
        //总和
        double sum1 = peoples.stream().mapToDouble(x -> x.getId()).sum();
        System.out.println(sum1);
        System.out.println("=========================");
        //最大值
        Optional<Person> max = peoples.stream().max(Comparator.comparing(Person::getAge));
        System.out.println(max.get());
        System.out.println("=========================");
        //最小值
        Optional<Person> min = peoples.stream().min((x, y) -> x.getId().compareTo(y.getId()));
        System.out.println(min.get());
        System.out.println("=========================");
        //分组
        Map<String, List<Person>> collect2 = peoples.stream().collect(Collectors.groupingBy(x -> x.getName()));
        System.out.println(collect2);
    }
}
